package com.education.welco.controller;

import com.education.common.core.BaseController;
import com.education.common.pojo.AjaxResult;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.utils.FileUtils;
import com.education.welco.enums.FileTypeEnum;
import com.education.welco.pojo.PlatformResources;
import com.education.welco.pojo.UserStar;
import com.education.welco.pojo.vo.UserStarVo;
import com.education.welco.service.IPlatformResourcesService;
import com.education.welco.service.IUserStarService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 资源用户星标（收藏关联） controller业务
 *
 * @Author: liftsail
 * @Date: 2022-09-23
 * @Description: 不积跬步无以至千里
 */
@RestController
@RequestMapping("/userStar")
public class UserStarController extends BaseController {

    @Autowired
    private IUserStarService userStarService;

    @Autowired
    private IPlatformResourcesService platformResourcesService;

    //查询学校   /api/wisdom/jrSchool/selectAll
    //select id, school_phone, school_name, create_time, introduction, logo, type from jr_school

    //星标回显
    //(select !is_delete from user_star where res_id = pr.id and user_id = pr.user_id) as starState

    /**
     * 平台端查询；星标列表
     * 星标文件list查找
     * 列表查询资源用户星标（收藏关联）
     * private Integer userId;
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam("userId") Integer userId,
                           @RequestParam(value = "fileName", required = false) String fileName,
                           @RequestParam(value = "fileType", required = false) FileTypeEnum fileType,
                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        //PageInfo<PlatformResources> fileListPage = platformResourcesService.listTheDirForStarList(userStar, pageNum, pageSize);
        //return AjaxResult.success("查询成功！", fileListPage);


        //名字和后缀
        if (fileType != null && StringUtils.isNotEmpty(fileName)) {
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(userId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(userId, ridCollect, fileName, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (fileType != null) {
            //后缀查询
            if (fileType == FileTypeEnum.ALL) {
                //没条件
                List<PlatformResources> platResourceShareList = userStarService.selectShareSchoolResListForStarByTeaId(userId, pageNum, pageSize);
                PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
                return AjaxResult.success("查询成功！", platformResourcesPageInfo);
            }
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(userId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(userId, ridCollect, null, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (StringUtils.isNotEmpty(fileName)) {
            //模糊查
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(userId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(userId, ridCollect, fileName, null, null, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else {
            //没条件
            List<PlatformResources> platResourceShareList = userStarService.selectShareSchoolResListForStarByTeaId(userId, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
    }


    /**
     * 新增保存资源用户星标（收藏关联）
     * 星标回调的逻辑
     *
     * @Param resId
     * @Param userId
     */
    @PostMapping("/addStar")
    public AjaxResult addSave(@RequestBody UserStarVo userStarVo) {
        //检查用户是否之前存在
        UserStar userStar = userStarService.selectUserStarByResIdAndUserId(userStarVo.getResId(), userStarVo.getUserId());
        //存在走修改状态业务
        if (Objects.nonNull(userStar)) {
            UserStar userStarcp = new UserStar();
            userStarcp.setResId(userStar.getResId());
            userStarcp.setUserId(userStar.getUserId());
            userStarcp.setIsDelete(false);
            userStarService.updateUserStarByResIdAndUserId(userStarcp);
            //状态判定
            if (userStar.getIsDelete()) {
                return AjaxResult.success("星标成功！");
            }
            return AjaxResult.success("取消星标成功！");
        }
        //不存在走新增业务
        userStarService.insertUserStar(userStarVo);
        return AjaxResult.success("星标成功！");
    }


    /**
     * 批量新增保存资源用户星标（收藏关联）
     *
     * @Param resIdList
     * @Param userId
     */
    @PostMapping("/batch/addStar")
    public AjaxResult batchAddSave(@RequestBody UserStarVo userStarVo) {
        //检查用户之前已经星标资源列表
        List<UserStar> userStarListBefore = userStarService.selectUserStarByUserIdAndResidList(userStarVo.getUserId(), userStarVo.getResIdList());
        List<String> resIdListBefore = userStarListBefore.parallelStream().map(userStar -> userStar.getResId()).collect(Collectors.toList());
        //现在需要星标的资源id
        List<String> resIdListUserNow = userStarVo.getResIdList();
        //从现在列表中移除数据库中存在的
        resIdListUserNow.removeIf(resId -> resIdListBefore.contains(resId));

        //1.批量更改状态-resIdListBefore
        if (resIdListBefore != null && resIdListBefore.size() > 0) {
            int i = userStarService.batchUpdateUserStarByResIdListAndUserId(resIdListBefore, userStarVo.getUserId(), false);
        }
        //2.批量插入数据-resIdListUserNow
        if (resIdListUserNow != null && resIdListUserNow.size() > 0) {
            int j = userStarService.batchInsertUserStarByResIdListAndUserId(resIdListUserNow, userStarVo.getUserId(), false);
        }
        return AjaxResult.success("批量星标成功！");
    }


    /**
     * 主键详情资源用户星标（收藏关联）
     */
    @GetMapping("/selectOne")
    public AjaxResult selectOne(Integer id) {
        UserStar result = userStarService.selectUserStarById(id);
        return AjaxResult.success("查询成功！", result);
    }

    /**
     * 修改保存资源用户星标（收藏关联）
     */
    @PostMapping("/update")
    public AjaxResult editSave(@RequestBody UserStar userStar) {
        userStarService.updateUserStar(userStar);
        return AjaxResult.success("修改成功！");
    }

    /**
     * 删除资源用户星标（收藏关联）
     * 用户取消星标
     */
    //@PostMapping("/delStar")
    //public AjaxResult remove(@RequestBody UserStarVo userStarVo) {
    //    //int i = userStarService.deleteUserStarByResIdAndUserId(userStarVo.getResId(), userStarVo.getUserId());
    //    if (Objects.nonNull(userStarVo)) {
    //        UserStar userStarcp = new UserStar();
    //        userStarcp.setResId(userStarVo.getResId());
    //        userStarcp.setUserId(userStarVo.getUserId());
    //        userStarcp.setIsDelete(false);
    //        userStarService.updateUserStarByResIdAndUserId(userStarcp);
    //        return AjaxResult.success("取消星标成功！");
    //    }
    //    return AjaxResult.success("参数传递异常！");
    //}

    /**
     * 批量删除资源用户星标（收藏关联）
     * 用户批量取消星标
     */
    @PostMapping("/batch/delStar")
    public AjaxResult batchRemove(@RequestBody UserStarVo userStarVo) {
        //int i = userStarService.batchDeleteUserStarByResIdsAndUserId(userStarVo.getResIdList(), userStarVo.getUserId());

        //批量更改状态
        int i = userStarService.batchUpdateUserStarByResIdListAndUserId(userStarVo.getResIdList(), userStarVo.getUserId(), true);
        return AjaxResult.success("批量取消星标成功！");
    }


    //老师端查找学校资源-星标文件
    @GetMapping("/starSchResList")
    public ApiReturnObject shareSchResList(@RequestParam("teaId") Integer teaId,
                                           @RequestParam(value = "fileName", required = false) String fileName,
                                           @RequestParam(value = "fileType", required = false) FileTypeEnum fileType,
                                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        //名字和后缀
        if (fileType != null && StringUtils.isNotEmpty(fileName)) {
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, fileName, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "目录文件查询成功！", platformResourcesPageInfo);
            //return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (fileType != null) {
            //后缀查询
            if (fileType == FileTypeEnum.ALL) {
                //没条件
                List<PlatformResources> platResourceShareList = userStarService.selectShareSchoolResListForStarByTeaId(teaId, pageNum, pageSize);
                PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
                return new ApiReturnObject("200", "目录文件查询成功！", platformResourcesPageInfo);
                //return AjaxResult.success("查询成功！", platformResourcesPageInfo);
            }
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, null, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "目录文件查询成功！", platformResourcesPageInfo);
            //return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (StringUtils.isNotEmpty(fileName)) {
            //模糊查
            List<PlatformResources> platformResourcesList = userStarService.selectShareSchoolResListForStarByTeaId(teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, fileName, null, null, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "目录文件查询成功！", platformResourcesPageInfo);
            //return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else {
            //没条件
            List<PlatformResources> platResourceShareList = userStarService.selectShareSchoolResListForStarByTeaId(teaId, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return new ApiReturnObject("200", "目录文件查询成功！", platformResourcesPageInfo);
            //return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
    }
}